package com.baymax.study.tuLing.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NIOClient {
    private static final String HOST = "127.0.0.1";

    private static final int PORT = 8080;

    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) {
        try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("Connected to server...");
            socketChannel.configureBlocking(false);
            ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

            while (true) {
                System.out.print("Enter message (type 'exit' to quit): \n");
                String message = scanner.nextLine();

                if ("exit".equalsIgnoreCase(message)) {
                    break;
                }

                // 发送消息到服务器
                buffer.clear();
                buffer.put(message.getBytes());
                buffer.flip();
                while (buffer.hasRemaining()) {
                    socketChannel.write(buffer);
                }

                // 接收响应
                buffer.clear();
                int bytesRead = 0;
                while ((bytesRead = socketChannel.read(buffer)) == 0) {
                    // 非阻塞模式下等待数据到达
                    Thread.sleep(100);
                }

                if (bytesRead == -1) {
                    System.out.println("Server closed connection");
                    break;
                }

                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println("Server response: \n" + new String(bytes));
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}